<template>
  <div class="elderly-info-page">
    <!-- 1. 美化后的顶部个人信息卡片 -->
    <header class="profile-header">
      <div class="header-bg"></div>
      <div class="profile-card">
        <div class="profile-avatar">
          <span>{{ editableProfile.fullName?.charAt(0) }}</span>
        </div>
        <h2 class="name">{{ editableProfile.fullName || '暂无姓名' }}</h2>
        <div class="tags">
          <van-tag plain :type="gender === '男' ? 'primary' : gender === '女' ? 'danger' : 'default'">
            <van-icon :name="gender === '男' ? '男' : gender === '女' ? '女' : 'question-mark'" />
            {{ genderText }}
          </van-tag>
          <van-tag plain type="success">{{ age }}</van-tag>
          <van-tag :type="checkInStatusInfo.type">{{ checkInStatusInfo.text }}</van-tag>
        </div>
      </div>
    </header>

    <main class="profile-content">
      <!-- 2. 信息展示与编辑 -->
      <van-cell-group inset :title="isEditing ? '编辑档案信息' : '基本档案'">
        <!-- 编辑模式切换按钮 -->
        <template #title>
            <div class="cell-group-title">
                <span>{{ isEditing ? '编辑档案信息' : '基本档案' }}</span>
                <van-button 
                    :icon="isEditing ? 'success' : 'edit'"
                    :type="isEditing ? 'success' : 'default'"
                    size="mini" 
                    round
                    @click="toggleEditMode"
                >
                    {{ isEditing ? '保存' : '编辑' }}
                </van-button>
            </div>
        </template>

        <!-- 非编辑状态 -->
        <template v-if="!isEditing">
          <van-cell title="身份证号" :value="maskedIdCard" />
          <van-cell title="出生日期" :label="editableProfile.dateOfBirth" />
          <van-cell title="家庭住址" :label="editableProfile.address || '暂无地址'" />
        </template>
        <!-- 编辑状态 -->
        <template v-else>
          <van-field v-model="editableProfile.fullName" label="姓名" placeholder="请输入姓名" :error="nameError" :error-message="nameErrorMessage" clearable @blur="validateName" />
          <!-- 身份证号字段 -->
          <van-field 
            v-model="editableProfile.idCardNumber" 
            label="身份证号" 
            placeholder="请输入身份证号" 
            :error="idCardError" 
            :error-message="idCardErrorMessage" 
            clearable 
            @blur="validateIdCard"
          />
          <van-field v-model="editableProfile.dateOfBirth" label="出生日期" placeholder="请选择出生日期" type="date" />
          <van-field v-model="editableProfile.address" label="家庭住址" placeholder="请输入家庭住址" type="textarea" autosize />
          <van-field 
            v-model="editableProfile.gender" 
            label="性别" 
            placeholder="请输入性别" 
            clearable 
            :error="genderError" 
            :error-message="genderErrorMessage"
            @blur="validateGender"
          />
        </template>
      </van-cell-group>

      <!-- 在院信息 (只读) -->
      <van-cell-group inset title="在院信息">
        <van-cell title="所在房间" :value="originalProfile.bedId === '999999' ? '未入住' : originalProfile.bedId" />
        <van-cell title="健康状况" :label="originalProfile.healthStatus" />
      </van-cell-group>

      <!-- 紧急联系人 (可编辑) -->
      <van-cell-group inset title="紧急联系人">
         <template v-if="!isEditing">
          <van-cell title="联系人姓名" :value="editableProfile.emergencyContactName" />
          <van-cell title="联系人电话" :value="editableProfile.emergencyContactPhone">
             <template #value>
                <div class="phone-value">
                  <span>{{ editableProfile.emergencyContactPhone }}</span>
                  <van-button 
                    icon="phone-o" type="primary" size="mini" round class="call-btn"
                    @click="callEmergencyContact"
                  >呼叫</van-button>
                </div>
             </template>
          </van-cell>
         </template>
         <template v-else>
            <van-field v-model="editableProfile.emergencyContactName" label="联系人姓名" placeholder="请输入姓名" />
            <van-field v-model="editableProfile.emergencyContactPhone" label="联系人电话" placeholder="请输入电话" type="tel" />
         </template>
      </van-cell-group>

      <!-- 详细记录入口 (固定跳转) -->
      <van-cell-group inset title="详细记录">
        <van-cell title="健康数据" is-link icon="chart-trending-o" to="/elderly/health" />
        <van-cell title="用药信息" is-link icon="bag-o" to="/elderly/medication" />
        <van-cell title="护理记录" is-link icon="records-o" to="/elderly/care" />
      </van-cell-group>

      <van-cell-group inset title="绑定家属">
        <van-cell title="申请绑定家属" is-link icon="user-o" to="/elderly/bind" />
      </van-cell-group>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { showToast, showConfirmDialog } from 'vant';
import { searchElderlyProfiles, addElderlyProfile, getElderlyProfile, updateElderlyProfile } from '@/api/elderly';  // 引入 API
import { useElderlyStore } from '@/stores/elderlyStore';

const elderlyStore = useElderlyStore();

// 用户ID假设值
const userId = 444;  // 这里需要替换为实际的用户ID

// 原始数据，用于重置和展示不可编辑部分
const originalProfile = ref({
  fullName: '',
  idCardNumber: '',
  gender: '',
  dateOfBirth: '',
  healthStatus: '',
  address: '',
  emergencyContactName: '',
  emergencyContactPhone: '',
  checkInStatus: '未入住',
  bedId: '999999'
});

// 可编辑的数据副本，用于表单绑定
const editableProfile = ref({
  userId: '',
  fullName: '',
  idCardNumber: '',
  gender: '',
  dateOfBirth: '',
  healthStatus: '',
  address: '',
  emergencyContactName: '',
  emergencyContactPhone: '',
  checkInStatus: '未入住',
  bedId: '999999'
});

// 当前档案 ID
const profileId = ref(null);

// 编辑模式状态
const isEditing = ref(false);

// 编辑模式切换按钮
const toggleEditMode = async () => {
  if (isEditing.value) {
    // 点击 "保存"
    saveProfile();
  } else {
    // 点击 "编辑"
    await fetchProfile();  // 查询档案信息
    isEditing.value = true;
    showToast('已进入编辑模式');
  }
};

// 添加档案方法
const addProfile = async () => {
  try {
    editableProfile.value.userId = userId;
    // console.log(editableProfile.value.userId)
    const result = await addElderlyProfile(editableProfile.value);
    profileId.value = result.id;  // 获取新创建的档案 ID
    originalProfile.value = { ...editableProfile.value };  // 更新原始数据

    // 更新 Pinia store 中的老人信息
    elderlyStore.setElderlyInfo(editableProfile.value);

    isEditing.value = false;
    showToast('档案添加成功');
  } catch (error) {
    showToast('添加档案失败');
  }
};

// 添加档案校验
const nameError = ref(false);
const nameErrorMessage = ref('');

const idCardError = ref(false);
const idCardErrorMessage = ref('');

const genderError = ref(false);
const genderErrorMessage = ref('');

// 校验姓名
const validateName = () => {
  if (!editableProfile.value.fullName) {
    nameError.value = true;
    nameErrorMessage.value = '姓名是必填项';
  } else {
    nameError.value = false;
    nameErrorMessage.value = '';
  }
};

// 校验身份证号
const validateIdCard = () => {
  if (!editableProfile.value.idCardNumber) {
    idCardError.value = true;
    idCardErrorMessage.value = '身份证号是必填项';
  } else {
    idCardError.value = false;
    idCardErrorMessage.value = '';
  }
};

// 校验性别
const validateGender = () => {
  if (!editableProfile.value.gender) {
    genderError.value = true;
    genderErrorMessage.value = '性别是必填项';
  } else {
    genderError.value = false;
    genderErrorMessage.value = '';
  }
};

// 提交表单时的校验
const submitForm = () => {
  validateName();
  validateIdCard();
  validateGender();

  if (!nameError.value && !idCardError.value && !genderError.value) {
    // 提交逻辑
    alert('表单提交成功');
  } else {
    alert('请填入所有必填项');
  }
};

// 保存档案信息
const saveProfile = async () => {
  showConfirmDialog({
    title: '确认保存',
    message: '您确定要保存修改后的信息吗？',
  })
  .then(async () => {
    // 用户点击了确认
    showToast({ type: 'loading', message: '保存中...', duration: 1000, forbidClick: true });

    // 保存用户档案，调用 updateElderlyProfile 更新档案
    try {
      if (profileId.value) {
        // 如果已有档案 ID，调用更新接口
        const result = await updateElderlyProfile(profileId.value, editableProfile.value);
        originalProfile.value = JSON.parse(JSON.stringify(editableProfile.value)); // 更新原始数据
        isEditing.value = false;

        // 更新 Pinia store 中的老人信息
        elderlyStore.setElderlyInfo(editableProfile.value);

        showToast('保存成功');
      } else {
        // 如果没有档案 ID，调用添加接口
        await addProfile();
      }
    } catch (error) {
      showToast('保存失败');
    }
  })
  .catch(() => {
    // 用户点击了取消
    showToast('已取消保存');
  });
};

// 获取用户档案信息
const fetchProfile = async () => {
  try {
    // 查询档案信息
    const result = await searchElderlyProfiles(userId, '', '', '', 1, 10);

    // 检查查询结果是否有效
    if (result.records && result.records.length > 0) {
      originalProfile.value = result.records[0];  // 设置原始档案数据
      editableProfile.value = { ...result.records[0] };  // 初始化可编辑数据
      profileId.value = result.records[0].id;  // 获取档案的 ID
      console.log(profileId.value)
    } else {
      // 如果没有档案信息，显示添加档案按钮
      editableProfile.value = {};  // 清空可编辑档案数据
      profileId.value = null;  // 清空档案 ID
      console.log('暂无档案')
    }
  } catch (error) {
    showToast('获取档案信息失败');
  }
};

// 计算年龄
const age = computed(() => {
  if (!originalProfile.value.dateOfBirth) return '年龄未知';
  const birthDate = new Date(originalProfile.value.dateOfBirth);
  const today = new Date();
  let age = today.getFullYear() - birthDate.getFullYear();
  const m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) age--;
  return age+'岁';
});

const gender = computed(() => originalProfile.value.gender);
const genderText = computed(() => gender.value === '男' ? '男' : (gender.value === '女' ? '女' : '性别未知'));


// 处理档案状态
const checkInStatusInfo = computed(() => {
  if (originalProfile.value.checkInStatus === '在住') {
    return { text: '在住', type: 'success' };
  }
  if (originalProfile.value.checkInStatus === '临时外出') {
    return { text: '临时外出', type: 'warning' };
  }
  if (originalProfile.value.checkInStatus === '退住') {
    return { text: '退住', type: 'danger' };
  }
  return { text: '未入住', type: 'default' };
});

const maskedIdCard = computed(() => {
  const id = originalProfile.value.idCardNumber;
  if (!id) return '';
  return `${id.slice(0, 4)}**********${id.slice(-4)}`;
});

const maskedPhone = computed(() => {
  const phone = originalProfile.value.phoneNumber;
  if (!phone) return '';
  return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
});


// 生命周期钩子：在页面加载时获取用户档案信息
onMounted(() => {
  fetchProfile();
});
</script>


<style scoped>
.elderly-info-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

/* 顶部美化 */
.profile-header {
  position: relative;
  height: 180px;
  margin-bottom: 80px; /* 为凸出的卡片留出空间 */
}
.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 150px;
  background: linear-gradient(135deg, #5c9cff 0%, #3a7afe 100%);
  border-bottom-left-radius: 20px;
  border-bottom-right-radius: 20px;
}
.profile-card {
  position: absolute;
  top: 60px;
  left: 16px;
  right: 16px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 8px 20px rgba(120, 120, 120, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  padding-top: 50px; /* 为头像留出空间 */
}
.profile-avatar {
  position: absolute;
  top: -40px; /* 将头像向上移动一半 */
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #3a7afe;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 40px;
  font-weight: bold;
  border: 4px solid #fff;
}
.profile-card .name {
  font-size: 22px;
  font-weight: bold;
  margin: 0 0 10px 0;
  color: #323233;
}
.profile-card .tags {
  display: flex;
  gap: 8px;
}

/* 主内容区域 */
.profile-content .van-cell-group {
  margin-bottom: 12px;
}
.cell-group-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* 电话呼叫按钮样式 */
.phone-value {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.call-btn {
  margin-left: 12px;
}

/* van-field 在编辑模式下的样式微调 */
:deep(.van-field__label) {
  width: 80px; /* 固定标签宽度，使输入框对齐 */
}
</style>